package com.mostromas.ess.oauth2.config;

import com.mostromas.ess.oauth2.authentication.HardwareCodingValidateFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 安全配置类
 */
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    private LogoutSuccessHandler customLogoutSuccessHandler;
    //校验机器码和用户名
    @Autowired
    private HardwareCodingValidateFilter hardwareCodingValidateFilter;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 读取用户信息进行认证
        auth.userDetailsService(userDetailsService);
    }
    @Bean // password 模式需要此 bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .addFilterBefore(hardwareCodingValidateFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin() // ++
                // 成功处理器
                .successHandler(customAuthenticationSuccessHandler)
                // 失败处理器
                .failureHandler(customAuthenticationFailureHandler)
            .and()
                .logout()
                // 退出成功处理器
                .logoutSuccessHandler(customLogoutSuccessHandler)
            .and()
                .csrf().disable();
    }
}
